<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="1000px"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        :disabled="!canEdit"
        v-loading="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务配置名称" prop="taskName">
              <el-input
                type="text"
                v-model="form.taskName"
                placeholder="请输入任务配置名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select
                v-model="form.taskType"
                placeholder="请选择任务类型"
                @change="handleTaskTypeChange"
              >
                <el-option
                  v-for="item in dict.taskType"
                  :key="item.codevalue"
                  :label="item.codename"
                  :value="item.codevalue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" class="template-col">
            <el-form-item label="任务模板" prop="taskTemplateCode">
              <el-select
                v-model="form.taskTemplateCode"
                filterable
                placeholder="请选择任务模板"
                @change="handleTaskTemplateCodeChange"
              >
                <el-option
                  v-for="item in taskTemplateCodeOptions"
                  :key="item.taskTemplateCode"
                  :label="item.taskTemplateName"
                  :value="item.taskTemplateCode"
                  :disabled="!!item.disabled"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-button
              type="text"
              class="preview-btn"
              :disabled="!form.taskTemplateCode"
              @click="handlePreviewTemplate"
              >预览</el-button
            >
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务性质" prop="taskNature">
              <el-radio-group
                v-model="form.taskNature"
                @change="resetFormField"
              >
                <el-radio
                  v-for="item in dict.taskNature"
                  :key="item.codevalue"
                  :label="item.codevalue"
                  >{{ item.codename }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属工厂" prop="ownedFactory">
              <el-select
                v-model="form.ownedFactory"
                placeholder="请选择所属工厂"
                :disabled="!!row || !!isWidthDevice"
                @change="handleFactoryChange"
              >
                <el-option
                  v-for="item in factoryList"
                  :key="item.factoryDeptCode"
                  :label="item.factoryName"
                  :value="item.factoryDeptCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属车间" prop="ownedWorkshop">
              <el-select
                v-model="form.ownedWorkshop"
                placeholder="请选择所属车间"
                clearable
                :disabled="!!isWidthDevice"
                @change="handleWorkshopChange"
              >
                <el-option
                  v-for="item in workShopList"
                  :key="item.workshopCode"
                  :label="item.workshopName"
                  :value="item.workshopCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属产线" prop="ownedProductionLine">
              <el-select
                v-model="form.ownedProductionLine"
                placeholder="请选择所属产线"
                clearable
                :disabled="!!isWidthDevice"
                @change="handleProductionLineChange"
              >
                <el-option
                  v-for="item in productionLineList"
                  :key="item.lineCode"
                  :label="item.lineName"
                  :value="item.lineCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属工序" prop="workSectionName">
              <el-input
                v-model="form.workSectionName"
                placeholder="请选择所属工序"
                readonly
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="openWorkSection"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="执行人" prop="operatorAndExecutiveAgency">
              <el-radio-group
                v-model="form.operatorType"
                @change="handleOperatorTypeChange"
              >
                <div style="margin-bottom: 10px">
                  <el-radio label="station">
                    <span style="margin-right: 10px">工位</span>
                    <el-select
                      v-model="form.station"
                      placeholder="请选择工位"
                      :disabled="form.operatorType != 'station'"
                      class="width220"
                    >
                      <el-option
                        v-for="item in stationList"
                        :key="item.workStationCode"
                        :label="item.workStationName"
                        :value="item.workStationCode"
                      >
                      </el-option>
                    </el-select>
                  </el-radio>
                </div>
                <div style="margin-bottom: 10px">
                  <el-radio label="job">
                    <span style="margin-right: 10px">岗位</span>
                    <el-select
                      v-model="form.position"
                      placeholder="请选择岗位"
                      :disabled="form.operatorType != 'job'"
                      class="width220"
                    >
                      <el-option
                        v-for="item in dict.PostManage"
                        :key="item.codevalue"
                        :label="item.codename"
                        :value="item.codevalue"
                      >
                      </el-option>
                    </el-select>
                  </el-radio>
                </div>
                <div>
                  <el-radio label="dept">
                    <span style="margin-right: 10px">部门</span>
                    <el-input
                      v-model="form.executiveAgencyName"
                      placeholder="请选择执行部门"
                      :disabled="form.operatorType != 'dept'"
                      class="width220"
                    >
                      <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click="openOrganization"
                      ></el-button>
                    </el-input>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <template v-if="form.taskType && form.taskNature">
          <!-- 周期性任务，显示频次配置 -->
          <el-row v-if="form.taskNature == '1'" :gutter="20">
            <el-col :span="24">
              <el-form-item label="任务频次" prop="frequency">
                <!-- 任务类型选择“生产准备任务”、“头班首检任务”时，显示“接班时下发任务”文本，非“生产准备任务”时显示任务频次 -->
                <div v-if="['1', '7'].includes(form.taskType)">
                  接班时下发任务
                </div>
                <div v-else>
                  <div class="in-row">
                    <span>每</span>
                    <el-input-number
                      v-model="form.frequency"
                      controls-position="right"
                      :min="1"
                      :max="
                        form.taskFrequency == '1'
                          ? 12
                          : form.taskFrequency == '2'
                          ? 14
                          : Infinity
                      "
                      style="width: 120px"
                    ></el-input-number>
                    <el-select
                      v-model="form.taskFrequency"
                      style="width: 120px"
                      @change="handleTaskFrequencyChange"
                    >
                      <el-option
                        v-for="item in dict.taskFrequency"
                        :key="item.codevalue"
                        :label="item.codename"
                        :value="item.codevalue"
                      >
                      </el-option>
                    </el-select>
                    <span>执行1次</span>
                  </div>
                  <div
                    class="tip"
                    v-if="['1', '2'].includes(form.taskFrequency)"
                  >
                    休息日不下发任务
                  </div>
                  <div class="tip" v-if="['3'].includes(form.taskFrequency)">
                    遇休息日则延至下一工作日下发任务
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="
              form.taskNature == '1' &&
              ['1', '2', '3'].includes(form.taskFrequency)
            "
            :gutter="20"
          >
            <el-col :span="12">
              <el-form-item label="生效时间" prop="effectiveDate">
                <!-- 若频次选择“小时、天”，则“生效时间”提供时间（年月日 时）组件； -->
                <!-- 若频次选择“月”，则“生效时间”提供时间（年月日）组件； -->
                <el-date-picker
                  v-if="['1', '2'].includes(form.taskFrequency)"
                  v-model="form.effectiveDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择生效时间"
                >
                </el-date-picker>
                <el-date-picker
                  v-if="['3'].includes(form.taskFrequency)"
                  v-model="form.effectiveDate"
                  type="date"
                  value-format="yyyy-MM-dd 00:00:00"
                  placeholder="请选择生效时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="form.taskNature == '1' && form.taskFrequency == '3'"
            :gutter="20"
          >
            <el-col :span="24">
              <el-form-item label="执行时间" prop="executeStartTime">
                <div class="in-row">
                  <el-time-picker
                    v-model="form.executeStartTime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择开始时间"
                  >
                  </el-time-picker>
                  至
                  <el-time-picker
                    v-model="form.executeEndTime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择结束时间"
                  >
                  </el-time-picker>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            v-if="form.taskNature == '1' && form.taskFrequency == '3'"
            :gutter="20"
          >
            <el-col :span="24">
              <el-form-item label="新增任务" prop="isEffectiveOriginPlan">
                <el-radio-group v-model="form.isEffectiveOriginPlan">
                  <el-radio label="N">不影响既定任务频次</el-radio>
                  <el-radio label="Y"
                    >执行任务则按频次更新后续任务开始时间</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 仅当“任务类型”选择“计划停机任务”时提供“标准作业时长”字段 -->
          <el-row v-if="form.taskType == '5'" :gutter="20">
            <el-col :span="12">
              <el-form-item label="标准作业时长" prop="standardOperatingTime">
                <div class="in-row">
                  <el-input
                    type="text"
                    v-model="form.standardOperatingTime"
                    placeholder="请输入标准作业时长"
                    style="width: 180px"
                  ></el-input>
                  <span>分钟</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 仅当频次是“月”时提供 -->
          <el-row
            v-if="form.taskNature == '1' && form.taskFrequency == '3'"
            :gutter="20"
          >
            <el-col :span="24">
              <el-form-item label="提醒时间" prop="remindBeforeTime">
                <el-radio-group v-model="form.isRemind">
                  <el-radio label="Y">
                    <span>
                      <span>任务开始前</span>
                      <el-input-number
                        v-model="form.remindBeforeTime"
                        controls-position="right"
                        :min="1"
                        :disabled="form.isRemind == 'N'"
                        style="width: 120px"
                      ></el-input-number>
                      <span>小时</span>
                    </span>
                  </el-radio>
                  <el-radio label="N">不提醒</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider></el-divider>
        </template>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否审核" prop="isExamine">
              <el-radio-group
                v-model="form.isExamine"
                @change="handleIsExamineChange"
              >
                <el-radio label="Y"> 是 </el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.isExamine == 'Y'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核人" prop="auditor" class="auditorGroup">
              <el-radio-group
                v-model="form.auditorType"
                @change="handleAuditorTypeChange"
              >
                <div style="margin-bottom: 10px">
                  <el-radio label="job">
                    <span style="margin-right: 10px">岗位</span>
                    <el-select
                      v-model="form.auditorPosition"
                      placeholder="请选择岗位"
                      :disabled="form.auditorType != 'job'"
                    >
                      <el-option
                        v-for="item in dict.PostManage"
                        :key="item.codevalue"
                        :label="item.codename"
                        :value="item.codevalue"
                      >
                      </el-option>
                    </el-select>
                  </el-radio>
                </div>
                <div>
                  <el-radio label="person">
                    <span style="margin-right: 10px">人员</span>
                    <el-input
                      v-model="form.auditorPersonName"
                      readonly
                      placeholder="请选择审核人"
                      :disabled="form.auditorType != 'person'"
                    >
                      <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click="openUserDialog"
                      ></el-button>
                    </el-input>
                  </el-radio>
                </div>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                v-model="form.remark"
                :rows="3"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          v-if="canEdit"
          type="primary"
          :loading="saveloading"
          @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 组织机构 -->
    <organizationDialog
      :branchcode="organizationDialog.branchinnercode"
      :visibles.sync="organizationDialog.visible"
      @closeDialog="closeOrganization"
    ></organizationDialog>

    <!-- 人员列表 -->
    <userList
      :visibles.sync="userDialog.visible"
      :multiple="true"
      :defaultValues="userDialog.defaultLineUsers"
      :branchinnercode="userDialog.branchinnercode"
      @closeDialog="closeUserDialog"
    ></userList>

    <!-- 工序列表 -->
    <SectionList
      :visible.sync="sectionDialog.visible"
      :multiple="true"
      :defaultValues="sectionDialog.defaultLineUsers"
      rowKey="workSectionCode"
      @closeDialog="closeWorkSection"
    ></SectionList>

    <!-- 表单预览 -->
    <PreviewDialog
      :visible.sync="previewDialog.visible"
      :formFieldConfig="previewDialog.formFieldConfig"
      :formName="previewDialog.formName"
      :renderingMode="previewDialog.renderingMode"
    ></PreviewDialog>
  </div>
</template>
<script>
import { checkPermi } from "@/utils/permission";
import {
  getTaskConfigDetail,
  saveTaskConfig,
} from "@/api/taskMgmt/configuration";
import {
  getTaskTemplateList,
  getTaskTemplateDesign,
} from "@/api/taskMgmt/template";
import { getEquipDetailByEquipIds } from "@/api/equipMgmt/equipment";
import SectionList from "@/views/components/sectionList";
import PreviewDialog from "../components/formDesign/previewDialog";
import WorkTree from "@/utils/workTree";
export default {
  components: { SectionList, PreviewDialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  dicts: ["PostManage","taskNature","taskFrequency","taskType"],
  data() {
    return {
      loading: false,
      form: {
        taskName: null,
        taskType: null,
        taskTemplateCode: null,
        taskNature: "1", //默认值
        ownedFactory: null,
        ownedWorkshop: null,
        executiveAgency: null,
        executiveAgencyName: null,
        ownedProductionLine: null,
        workSectionCode: null,
        workSectionName: null,
        operatorType: "station", ////默认工位
        operator: null,
        station: null,
        position: null,
        frequency: null,
        taskFrequency: null,
        effectiveDate: null,
        executeStartTime: null,
        executeEndTime: null,
        standardOperatingTime: null,
        isEffectiveOriginPlan: "N",
        isRemind: "Y",
        auditorType: "job",
        auditor: null,
        auditorName: null,
        auditorPerson: null,
        auditorPersonName: null,
        auditorPosition: null,
        status: null,
        remindBeforeTime: null,
        isExamine: "N",
        remark: null,
      },
      rules: {
        taskName: [
          { required: true, message: "请输入任务配置名称", trigger: "change" },
          {
            max: 30,
            message: "任务配置名称长度最多30个字符",
            trigger: "change",
          },
        ],
        taskType: [
          { required: true, message: "请选择任务类型", trigger: "change" },
        ],
        taskTemplateCode: [
          { required: true, message: "请选择任务模板", trigger: "change" },
        ],
        taskNature: [
          { required: true, message: "请选择任务性质", trigger: "change" },
        ],
        ownedFactory: [
          { required: true, message: "请选择所属工厂", trigger: "change" },
        ],
        ownedWorkshop: [
          { required: true, message: "请选择所属车间", trigger: "change" },
        ],
        ownedProductionLine: [
          { required: true, message: "请选择所属产线", trigger: "change" },
        ],
        operatorAndExecutiveAgency: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.form.taskNature == "1") {
                // 周期性
                if (
                  !this.form.operator &&
                  !this.form.executiveAgency &&
                  !this.form.executiveAgencyName
                ) {
                  callback(new Error("请选择执行人"));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            message: "请选择执行人",
            trigger: "change",
          },
        ],
        executiveAgencyName: [
          { required: true, message: "请选择执行部门", trigger: "change" },
        ],
        frequency: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (["1", "7"].includes(this.form.taskType)) {
                callback();
                return;
              }
              if (!this.form.frequency || !this.form.taskFrequency) {
                callback(new Error("请输入任务频次"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
        effectiveDate: [
          { required: true, message: "请选择生效时间", trigger: "change" },
        ],
        executeStartTime: [
          { required: true, message: "请选择执行时间", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              if (!this.form.executeStartTime || !this.form.executeEndTime) {
                callback(new Error("请选择执行时间"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
        standardOperatingTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback();
              } else if (/^\d{1,3}$/.test(value) && Number(value) > 0) {
                callback();
              } else {
                callback(new Error("请输入大于0的正整数，最大3位数"));
              }
            },
            trigger: "change",
          },
        ],
        remindBeforeTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.form.isRemind == "Y" && !this.form.remindBeforeTime) {
                callback(new Error("请输入提醒时间"));
                return;
              }
              callback();
            },
            trigger: "change",
          },
        ],
        isExamine: [
          { required: true, message: "请选择是否审核", trigger: "change" },
        ],
        auditor: [
          { required: true, message: "请选择审核人", trigger: "change" },
        ],
        remark: [{ max: 200, message: "备注字符长度最长200个" }],
      },
      taskTemplateCodeOptions: [], //任务模板列表
      taskTempalteDisableOption: null,
      workTree: null,
      factoryList: [], //工厂列表
      deptList: [], //部门列表
      workShopList: [], //车间列表
      productionLineList: [], //产线列表
      stationList: [], //工位列表
      organizationDialog: {
        visible: false,
        branchinnercode: null,
      },
      userDialog: {
        visible: false,
        branchinnercode: null,
        defaultLineUsers: [],
      },
      sectionDialog: {
        visible: false,
        defaultLineUsers: [],
      },
      // 表单预览弹窗
      previewDialog: {
        visible: false,
        formFieldConfig: {},
        formName: null,
        renderingMode: "1",
      },
      saveloading: false,
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    title() {
      if (this.disabled == true) {
        return "任务配置详情";
      }
      if (!!this.row) {
        return "编辑任务配置";
      }
      return "新增任务配置";
    },
    canEdit() {
      if (this.disabled == true) {
        return false;
      }
      if (this.row?.id) {
        return checkPermi(["taskMgmt:configuration:edit"]);
      }
      return true;
    },
    // 选中的模板对象
    taskTemplateItem() {
      if (!this.form.taskTemplateCode) {
        return {};
      }
      const item = this.taskTemplateCodeOptions.find(
        (ele) => ele.taskTemplateCode == this.form.taskTemplateCode
      );
      return item || {};
    },
    // 若所选模板关联有车间-产线信息的设备，则自动获取设备关联的车间-产线并填充至任务所属车间、产线，不支持修改；
    // 如未关联，则可手动设置所属车间、产线
    // 是否关联
    isWidthDevice() {
      return (
        this.taskTemplateItem?.associatedDevice &&
        this.form.ownedFactory &&
        this.form.ownedWorkshop &&
        this.form.ownedProductionLine
      );
    },
  },
  async created() {
    // 工厂-车间-产线-工序-工位
    this.workTree = new WorkTree();
    await this.workTree.affterLoad();
    this.factoryList = this.workTree.getFactory();
  },
  methods: {
    handleClose() {
      this.form = {
        taskName: null,
        taskType: null,
        taskTemplateCode: null,
        taskNature: "1", //默认值
        ownedFactory: null,
        ownedWorkshop: null,
        executiveAgency: null,
        executiveAgencyName: null,
        ownedProductionLine: null,
        workSectionCode: null,
        workSectionName: null,
        operatorType: "station", ////默认工位
        operator: null,
        station: null,
        position: null,
        frequency: null,
        taskFrequency: null,
        effectiveDate: null,
        executeStartTime: null,
        executeEndTime: null,
        standardOperatingTime: null,
        isEffectiveOriginPlan: "N",
        isRemind: "Y",
        auditorType: "job",
        auditor: null,
        auditorName: null,
        auditorPerson: null,
        auditorPersonName: null,
        auditorPosition: null,
        status: null,
        remindBeforeTime: null,
        isExamine: "N",
        remark: null,
      };
      this.$refs.ruleForm.resetFields();
    },
    handleOpen() {
      this.getDetails();
    },
    getDetails() {
      if (!this.row?.id) {
        // 默认获取第一个工厂-车间-产线
        const results = this.getOwnFirstLine();
        this.form.ownedFactory = results[0]?.factoryDeptCode || "";
        this.form.ownedWorkshop = results[1]?.workshopCode || "";
        this.form.ownedProductionLine = results[2]?.lineCode || "";
        return;
      }
      this.loading = true;
      getTaskConfigDetail(this.row.id)
        .then((res) => {
          const {
            taskCode,
            taskName,
            taskType,
            taskTemplateCode,
            taskTemplateName,
            taskFormName,
            renderingMode,
            taskNature,
            ownedFactory,
            ownedWorkshop,
            executiveAgency,
            executiveAgencyName,
            ownedProductionLine,
            workSectionCode,
            workSectionName,
            operatorType,
            operator,
            frequency,
            taskFrequency,
            effectiveDate,
            executeStartTime,
            executeEndTime,
            standardOperatingTime,
            isEffectiveOriginPlan,
            isRemind,
            auditorType,
            auditor,
            auditorName,
            status,
            remindBeforeTime,
            isExamine,
            remark,
          } = res.data;
          this.form = {
            taskName,
            taskType,
            taskTemplateCode,
            taskNature: taskNature == null ? "1" : taskNature,
            ownedFactory,
            ownedWorkshop,
            executiveAgency,
            executiveAgencyName,
            ownedProductionLine,
            workSectionCode,
            workSectionName,
            operatorType: operatorType || "station",
            operator,
            station: operatorType == "station" ? operator : null,
            position: operatorType == "job" ? operator : null,
            frequency,
            taskFrequency,
            effectiveDate,
            executeStartTime,
            executeEndTime,
            standardOperatingTime,
            isEffectiveOriginPlan: isEffectiveOriginPlan || "N",
            isRemind: isRemind == null ? "Y" : isRemind,
            auditorType,
            auditor,
            auditorName,
            auditorPerson: auditorType == "person" ? auditor : null,
            auditorPersonName: auditorType == "person" ? auditorName : null,
            auditorPosition: auditorType == "job" ? auditor : null,
            status,
            remindBeforeTime,
            isExamine: isExamine || "N",
            remark,
          };
          this.taskTempalteDisableOption = {
            taskCode,
            taskTemplateCode,
            taskTemplateName,
            taskFormName,
            renderingMode: renderingMode || "1",
          };
          this.loading = false;
        })
        .catch(() => {
          this.form = {
            taskName: null,
            taskType: null,
            taskTemplateCode: null,
            taskNature: "1", //默认值
            ownedFactory: null,
            ownedWorkshop: null,
            executiveAgency: null,
            executiveAgencyName: null,
            ownedProductionLine: null,
            workSectionCode: null,
            workSectionName: null,
            operatorType: "station", ////默认工位
            operator: null,
            station: null,
            position: null,
            frequency: null,
            taskFrequency: null,
            effectiveDate: null,
            executeStartTime: null,
            executeEndTime: null,
            standardOperatingTime: null,
            isEffectiveOriginPlan: "N",
            isRemind: "Y",
            auditorType: "job", //默认岗位
            auditor: null,
            auditorName: null,
            auditorPerson: null,
            auditorPersonName: null,
            auditorPosition: null,
            status: null,
            remindBeforeTime: null,
            isExamine: "N",
            remark: null,
          };
          this.taskTempalteDisableOption = null;
          this.loading = false;
        });
    },
    // 获取任务模板列表
    getTaskTemplateCodeOptions(taskType) {
      if (!taskType) {
        this.taskTemplateCodeOptions = [];
        return;
      }
      const param = {
        pageNum: 1,
        pageSize: 2000,
        query: {
          templateName: "",
          taskType,
          status: "1", //启用的
          templateCategory: "custom",
        },
      };
      getTaskTemplateList(param)
        .then((res) => {
          this.taskTemplateCodeOptions = res.rows || [];

          // 如果列表中不存在配置的模板(模板被禁用或被删除),则通过详情的taskTemplateCode/taskTemplateName添加一个被禁用的选项
          const formTaskTemplateCode = this.form.taskTemplateCode;
          if (formTaskTemplateCode) {
            const hasItem = this.taskTemplateCodeOptions.find(
              (ele) => ele.taskTemplateCode == formTaskTemplateCode
            );

            if (!hasItem && this.taskTempalteDisableOption) {
              this.taskTemplateCodeOptions.unshift({
                taskCode: this.taskTempalteDisableOption.taskCode,
                taskTemplateCode:
                  this.taskTempalteDisableOption.taskTemplateCode,
                taskTemplateName:
                  this.taskTempalteDisableOption.taskTemplateName,
                taskFormName: this.taskTempalteDisableOption.taskFormName,
                renderingMode: this.taskTempalteDisableOption.renderingMode,
                disabled: true,
              });
            }
          }
        })
        .catch(() => {
          this.list = [];
        });
    },
    handleSubmit() {
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          this.saveloading = true;

          const _form = this.form;
          let params = {
            id: this.row?.id || "",
            taskName: _form.taskName || "",
            taskType: _form.taskType || "",
            taskTemplateCode: _form.taskTemplateCode || "",
            taskNature: _form.taskNature || "",
            ownedFactory: _form.ownedFactory || "",
            ownedWorkshop: _form.ownedWorkshop || "",
            ownedProductionLine: _form.ownedProductionLine || "",
            workSectionCode: _form.workSectionCode || "",
            operatorType: _form.operatorType || "",
            operator: _form.operator || "",
            executiveAgency: _form.executiveAgency || "",
            effectiveDate: _form.effectiveDate || "",
            frequency: _form.frequency || null,
            taskFrequency: _form.taskFrequency || "4", // 任务频次为“接班时下发任务”时，taskFrequency传4
            executeStartTime: _form.executeStartTime || "",
            executeEndTime: _form.executeEndTime || "",
            standardOperatingTime: _form.standardOperatingTime || "",
            isRemind: _form.isRemind || "",
            remindBeforeTime: _form.remindBeforeTime || "",
            isExamine: _form.isExamine || "",
            auditorType: _form.auditorType || "job",
            auditor: _form.auditor || "",
            auditorName: _form.auditorName || "",
            status: _form.status || "0",
            isEffectiveOriginPlan: _form.isEffectiveOriginPlan || "N",
            isConcernedTask: _form.isConcernedTask || "",
            remark: _form.remark || "",
          };

          saveTaskConfig(params)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess("保存成功!");
                this.$emit("refresh");
                this.dialogVisible = false;
              }
            })
            .finally(() => {
              this.saveloading = false;
            });
        }
      });
    },
    // 重新更新部分字段（切换任务类型、任务性质时）
    resetFormField(value) {
      // 清空数据
      this.form.frequency = null;
      this.form.taskFrequency = "";
      this.form.effectiveDate = "";
      this.form.executeStartTime = "";
      this.form.executeEndTime = "";
      this.form.standardOperatingTime = "";
      this.form.isEffectiveOriginPlan = "N";
      this.form.isRemind = "Y";
      this.form.remindBeforeTime = "";

      this.$refs.ruleForm.clearValidate();
    },
    handleTaskTypeChange() {
      this.form.taskTemplateCode = null;
      this.resetFormField();
    },
    handleTaskTemplateCodeChange() {
      // 若所选模板关联有车间产线的设备，自动带出设备的车间产线并不可修改，否则可以手动设置
      if (this.taskTemplateItem?.associatedDevice) {
        getEquipDetailByEquipIds(this.taskTemplateItem.associatedDevice).then(
          (res) => {
            const data = res.data[0];
            this.form.ownedFactory = data?.factoryDeptCode || null;
            this.form.ownedWorkshop = data?.workshopDto?.workshopCode || null;
            this.form.ownedProductionLine =
              data?.erpProductionLineDto?.erpProductionLineCode || null;
          }
        );
      }
    },
    handleFactoryChange(value) {
      this.form.ownedWorkshop = "";
      this.form.ownedProductionLine = "";
      this.resetOperatorByBelong();
    },
    handleWorkshopChange(value) {
      this.form.ownedProductionLine = "";
      this.resetOperatorByBelong();
    },
    handleProductionLineChange(value) {
      this.resetOperatorByBelong();
    },
    handleOperatorTypeChange(value) {
      this.form.operator = "";
      this.form.station = "";
      this.form.position = "";
      this.form.executiveAgency = "";
      this.form.executiveAgencyName = "";
    },
    resetOperatorByBelong() {
      if (this.form.operatorType == "station") {
        this.form.operator = "";
        this.form.station = "";
        this.form.position = "";
        this.form.executiveAgency = "";
        this.form.executiveAgencyName = "";
      }
    },
    openOrganization() {
      if (this.form.operatorType != "dept") {
        return;
      }
      if (!this.form.ownedFactory) {
        this.msgWarning("请先选择所属工厂！");
        return;
      }
      // 默认组织筛选条件
      const item = this.factoryList.find(
        (ele) => ele.factoryDeptCode == this.form.ownedFactory
      );
      this.organizationDialog.branchinnercode = item?.factoryDeptId || null;
      this.organizationDialog.visible = true;
    },
    closeOrganization(list) {
      if (list?.length) {
        this.form.executiveAgency = list[0].code;
        this.form.executiveAgencyName = list[0].label;
      } else {
        this.form.executiveAgency = "";
        this.form.executiveAgencyName = "";
      }
    },
    handleIsExamineChange(value) {
      if (value == "N") {
        this.form.auditorType = "job"; //默认岗位
        this.form.auditor = "";
        this.form.auditorName = "";
        this.form.auditorPerson = "";
        this.form.auditorPersonName = "";
        this.form.auditorPosition = "";
      }
    },
    handleAuditorTypeChange() {
      this.form.auditor = "";
      this.form.auditorName = "";
      this.form.auditorPerson = "";
      this.form.auditorPersonName = "";
      this.form.auditorPosition = "";
    },
    handleTaskFrequencyChange(value) {
      if (value == "1") {
        if (this.form.frequency > 12) {
          this.form.frequency = 12;
        }
      } else if (value == "2") {
        if (this.form.frequency > 14) {
          this.form.frequency = 14;
        }
      }
    },
    openUserDialog() {
      if (this.form.isExamine != "Y") {
        return;
      }
      if (!this.form.ownedFactory) {
        this.msgWarning("请先选择所属工厂！");
        return;
      }

      // 默认组织筛选条件
      const item = this.factoryList.find(
        (ele) => ele.factoryDeptCode == this.form.ownedFactory
      );
      this.userDialog.branchinnercode = item?.factoryDeptId || "";

      // 默认选中人
      const _auditorPerson = this.form.auditorPerson
        ? this.form.auditorPerson.split(",")
        : [];
      const _auditorPersonName = this.form.auditorPersonName
        ? this.form.auditorPersonName.split(",")
        : [];

      let _defaultLineUsers = [];
      _auditorPerson.forEach((ele, i) => {
        _defaultLineUsers.push({
          username: ele,
          realname: _auditorPersonName[i],
        });
      });

      this.userDialog.defaultLineUsers = _defaultLineUsers;

      this.userDialog.visible = true;
    },
    closeUserDialog(list) {
      if (!list) {
        return;
      }

      this.form.auditorPerson = list.map((ele) => ele.username).join(",");
      this.form.auditorPersonName = list.map((ele) => ele.realname).join(",");
    },
    openWorkSection() {
      let _workSectionCode = [];
      let _workSectionName = [];

      if (this.form.workSectionCode) {
        _workSectionCode = this.form.workSectionCode.split(",") || [];
        _workSectionName = this.form.workSectionName.split(",") || [];
      }

      let defaultLineUsers = [];
      _workSectionCode.forEach((ele, i) => {
        defaultLineUsers.push({
          workSectionCode: ele,
          workSectionName: _workSectionName[i],
        });
      });
      this.sectionDialog.defaultLineUsers = defaultLineUsers;
      this.sectionDialog.visible = true;
    },
    closeWorkSection(list) {
      if (!list?.length) {
        this.form.workSectionCode = "";
        this.form.workSectionName = "";
        return;
      }
      let _workSectionCode = [];
      let _workSectionName = [];

      list.forEach((ele) => {
        _workSectionCode.push(ele.workSectionCode);
        _workSectionName.push(ele.workSectionName);
      });

      this.form.workSectionCode = _workSectionCode.join(",");
      this.form.workSectionName = _workSectionName.join(",");
    },
    handlePreviewTemplate() {
      const _taskTemplateCode = this.form.taskTemplateCode;
      if (!_taskTemplateCode) {
        return;
      }
      const row = this.taskTemplateCodeOptions.find(
        (ele) => ele.taskTemplateCode == _taskTemplateCode
      );
      if (!row) {
        return;
      }
      getTaskTemplateDesign(_taskTemplateCode, row.taskCode || undefined)
        .then((res) => {
          this.previewDialog.formFieldConfig = res.data;
          this.previewDialog.formName = row.taskFormName;
          this.previewDialog.renderingMode = row.renderingMode;
          this.previewDialog.visible = true;
        })
        .catch(() => {});
    },
  },
  watch: {
    "form.taskType": {
      handler(newVal) {
        this.getTaskTemplateCodeOptions(newVal);
      },
    },
    "form.taskNature": {
      handler(newVal) {
        if (newVal == "1") {
          // 周期性
          this.rules.ownedWorkshop[0].required = true;
          this.rules.ownedProductionLine[0].required = true;
          this.rules.operatorAndExecutiveAgency[0].required = true;
        } else if (newVal == "2") {
          // 一次性
          this.rules.ownedWorkshop[0].required = false;
          this.rules.ownedProductionLine[0].required = false;
          this.rules.operatorAndExecutiveAgency[0].required = false;
        }
      },
    },
    "form.ownedFactory": {
      handler(newVal) {
        if (newVal) {
          this.workShopList = this.workTree.getWorkshop({
            factoryDeptCode: newVal,
          });
        } else {
          this.workShopList = [];
        }
      },
    },
    "form.ownedWorkshop": {
      handler(newVal) {
        if (newVal) {
          this.productionLineList = this.workTree.getProductionLine({
            workshopCode: newVal,
          });
        } else {
          this.productionLineList = [];
        }
      },
    },
    "form.ownedProductionLine": {
      handler(newVal) {
        if (newVal) {
          this.stationList = this.workTree.getWorkStation({
            lineCode: newVal,
          });
        } else {
          this.stationList = [];
        }
      },
    },
    "form.station": {
      handler(newVal) {
        this.form.operator = newVal; // || this.form.position;
      },
    },
    "form.position": {
      handler(newVal) {
        this.form.operator = newVal; // || this.form.station;
      },
    },
    "form.auditorPosition": {
      handler(newVal) {
        this.form.auditor = newVal;
        this.form.auditorName = "";
      },
    },
    "form.auditorPersonName": {
      handler(newVal) {
        this.form.auditor = this.form.auditorPerson;
        this.form.auditorName = newVal;
      },
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__content {
  & > .el-select {
    width: 100%;
  }
}
.el-divider--horizontal {
  margin: 0 0 24px;
}
.in-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
}
::v-deep .el-form-item__content {
  .el-input-group {
    vertical-align: middle;
  }
}
.width220 {
  width: 220px;
}
.template-col {
  position: relative;
  .preview-btn {
    position: absolute;
    right: 6px;
    top: 0;
    transform: translateX(100%);
  }
}
</style>
